package com.caration.shell.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.view.View;
import android.view.ViewGroup;

public final class Reflect {

	private static Method sSetLayerType;
	private static Method sSetMotionEventSplittingEnabled;
	private static Method sCreateClipTable;

	static {
		Class<?> paramsType[] = new Class[] { Integer.TYPE, Paint.class };
		sSetLayerType = getMethodInstance(View.class, "setLayerType",
				paramsType);

		paramsType = new Class[] { Boolean.TYPE };
		sSetMotionEventSplittingEnabled = getMethodInstance(ViewGroup.class,
				"setMotionEventSplittingEnabled", paramsType);

		paramsType = new Class[] { Integer.TYPE, Integer.TYPE };
		Class<?> classInstance = null;
		try {
			classInstance = Class.forName("android.graphics.TableMaskFilter");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		sCreateClipTable = getMethodInstance(classInstance, "CreateClipTable",
				paramsType);
	}

	private static Method getMethodInstance(Class<?> targetClass,
			String methodName, Class<?> paramsType[]) {
		Method method = null;
		try {
			method = targetClass.getMethod(methodName, paramsType);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			method = null;
		}
		return method;
	}

	/**
	 * ViewGroup -> setMotionEventSplittingEnabled(ViewGroup,Boolean)
	 * 
	 * @param viewgroup
	 */
	public static void setMotionEventSplittingDisable(ViewGroup viewgroup) {
		if (sSetMotionEventSplittingEnabled != null) {
			try {
				sSetMotionEventSplittingEnabled.invoke(null, viewgroup, false);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * View -> setLayerType(int , Paint )
	 * 
	 * @param i
	 * @param p
	 */
	public static void setLayerType(int i, Paint p) {
		if (sSetLayerType != null) {
			try {
				sSetLayerType.invoke(null, i, p);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * android.graphics.TableMaskFilter -> createClipTable(int min,int max)
	 * 
	 * @param min
	 * @param max
	 * @return TableMaskFilter
	 */
	public static MaskFilter createClipTable(int min, int max) {
		MaskFilter maskFilter = null;
		if (sCreateClipTable != null) {
			try {
				maskFilter = (MaskFilter) sCreateClipTable.invoke(null, min,
						max);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return maskFilter;
	}
}
